package com.team.easybuy.controller;

import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.team.easybuy.entity.Order;
import com.team.easybuy.service.OrderService;
import com.team.easybuy.util.AliPayUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yan
 * @date 2022-06-29 09:07:45
 * @description
 */
@Controller
@RequestMapping("/api/pay")
public class AliPayController {

    @Resource
    private AliPayUtil aliPayUtil;

    @Resource
    private OrderService orderService;

    @RequestMapping("/alipay")
    @ResponseBody
    public String aliPay(@RequestBody Order order) {
        String result = "";
        try {
            result = aliPayUtil.toPCPay(order.getLoginName() + "的订单", order.getSerialNumber(), order.getCost().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/returnDeal")
    public String returnDeal(HttpServletRequest request) throws Exception {
        //1.验签,判断数据是不是来自支付宝
        Map<String, String[]> params = request.getParameterMap();  //支付宝给我们返回的数据,value只有第0个位置有数据
        Map<String, String> paramster = new HashMap<>();   //生成一个map，用来存放支付宝返回的数据
        params.entrySet();
        //遍历map
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            entry.getKey();
            entry.getValue();
            paramster.put(entry.getKey(), entry.getValue()[0]);
        }
        boolean flag = aliPayUtil.validateSign(paramster);
        if (!flag) {
            return "failed";
        }
        System.out.println(paramster);
        //2.获取参数
        String out_trade_no = paramster.get("out_trade_no"); //商户订单号
        //3.数据库操作
        orderService.updatePayType(out_trade_no);
        return "redirect:/Success.html";
    }

    @RequestMapping("/toRefund")
    @ResponseBody
    public String refund(@RequestBody Order order) {
        String result = "";
        try {
            result = aliPayUtil.refund(order.getSerialNumber(), order.getCost().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        orderService.refund(order.getId());
        return result;
    }
}
